package com.trumeen.immichgallery.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.trumeen.immichgallery.model.AppSettings
import com.trumeen.immichgallery.model.Asset
import com.trumeen.immichgallery.model.ImageSwitchPeriod
import com.trumeen.immichgallery.model.ImageType
import com.trumeen.immichgallery.repository.AuthManager
import com.trumeen.immichgallery.repository.NetworkRepository
import com.trumeen.immichgallery.repository.SettingsDataStore
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.threeten.bp.Instant
import org.threeten.bp.ZoneId
import org.threeten.bp.format.DateTimeFormatter
import javax.inject.Inject

@HiltViewModel
class MainViewModel @Inject constructor(
    private val networkRepository: NetworkRepository,
    private val authManager: AuthManager,
    private val settingsDataStore: SettingsDataStore
) : ViewModel() {

    private val _assets = MutableStateFlow<List<Asset>>(emptyList())
    val assets: StateFlow<List<Asset>> = _assets.asStateFlow()

    private val _currentIndex = MutableStateFlow(0)
    val currentIndex: StateFlow<Int> = _currentIndex.asStateFlow()

    private val _isLoading = MutableStateFlow(false)
    val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

    private val _errorMessage = MutableStateFlow<String?>(null)
    val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()

    private val _connectionStatus = MutableStateFlow(ConnectionStatus.NOT_CONNECTED)
    val connectionStatus: StateFlow<ConnectionStatus> = _connectionStatus.asStateFlow()

    private var slideshowJob: Job? = null
    private val _isPlaying = MutableStateFlow(false)
    val isPlaying: StateFlow<Boolean> = _isPlaying.asStateFlow()

    private var selectedImageType = ImageType.TODAY_IN_HISTORY
    private var switchPeriod = ImageSwitchPeriod.ONE_HOUR
    private var selectedPersonId = ""

    init {
        loadSettings()
        checkConnectionStatus()
    }

    private fun loadSettings() {
        viewModelScope.launch {
            settingsDataStore.appSettingsFlow.collect { settings ->
                selectedImageType = settings.imageType
                switchPeriod = settings.imageSwitchPeriod
                selectedPersonId = settings.selectedPersonId
                loadInitialAssets()
            }
        }
    }

    private fun checkConnectionStatus() {
        viewModelScope.launch {
            authManager.isAuthenticatedFlow.collect { isAuthenticated ->
                _connectionStatus.value = if (isAuthenticated) {
                    ConnectionStatus.CONNECTED
                } else {
                    ConnectionStatus.NOT_CONNECTED
                }
            }
        }
    }

    private fun loadInitialAssets() {
        viewModelScope.launch {
            if (!authManager.isAuthenticated()) {
                _errorMessage.value = "请先登录服务器"
                return@launch
            }

            _isLoading.value = true
            _errorMessage.value = null

            try {
                when (selectedImageType) {
                    ImageType.TODAY_IN_HISTORY -> loadOnThisDayAssets()
                    ImageType.SPECIFIC_PERSON -> {
                        if (selectedPersonId.isNotEmpty()) {
                            loadPersonAssets()
                        } else {
                            _errorMessage.value = "请先选择人物"
                        }
                    }
                    ImageType.LANDSCAPE -> {
                        // TODO: 实现风景图片加载逻辑
                        _errorMessage.value = "风景图片功能开发中"
                    }
                }
            } catch (e: Exception) {
                _errorMessage.value = "加载失败: ${e.message}"
                Log.e("MainViewModel", "加载图片失败", e)
            } finally {
                _isLoading.value = false
            }
        }
    }

    private suspend fun loadOnThisDayAssets() {
        val zoneId = ZoneId.of("Asia/Shanghai")
        val dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(zoneId)
        val dataTime = dateTimeFormatter.format(Instant.now())

        networkRepository.getOnThisDayImages(dataTime)
            .onSuccess { memoriesResponse ->
                val allAssets = memoriesResponse.flatMap { it.assets }
                    .filter { it.type == "IMAGE" }
                _assets.value = allAssets
                if (allAssets.isNotEmpty()) {
                    _currentIndex.value = 0
                } else {
                    _errorMessage.value = "没有找到那年今日的图片"
                }
            }
            .onFailure { error ->
                _errorMessage.value = "加载失败: ${error.message}"
            }
    }

    private suspend fun loadPersonAssets() {
        // TODO: 实现获取特定人物图片的逻辑
        _errorMessage.value = "人物图片功能开发中"
    }

    fun nextAsset() {
        if (_assets.value.isNotEmpty()) {
            _currentIndex.value = (_currentIndex.value + 1) % _assets.value.size
        }
    }

    fun previousAsset() {
        if (_assets.value.isNotEmpty()) {
            _currentIndex.value = if (_currentIndex.value == 0) {
                _assets.value.size - 1
            } else {
                _currentIndex.value - 1
            }
        }
    }

    fun startSlideshow() {
        if (_assets.value.isEmpty()) return

        _isPlaying.value = true
        slideshowJob?.cancel()

        slideshowJob = viewModelScope.launch {
            while (_isPlaying.value) {
                val delayMillis = when (switchPeriod) {
                    ImageSwitchPeriod.ONE_HOUR -> 3600000L
                    ImageSwitchPeriod.HALF_DAY -> 43200000L
                    ImageSwitchPeriod.ONE_DAY -> 86400000L
                }

                delay(delayMillis)
                if (_isPlaying.value && _assets.value.isNotEmpty()) {
                    nextAsset()
                }
            }
        }
    }

    fun stopSlideshow() {
        _isPlaying.value = false
        slideshowJob?.cancel()
    }

    fun clearError() {
        _errorMessage.value = null
    }

    fun updateImageType(imageType: ImageType) {
        selectedImageType = imageType
        loadInitialAssets()
    }

    fun updateSwitchPeriod(period: ImageSwitchPeriod) {
        switchPeriod = period
        if (_isPlaying.value) {
            stopSlideshow()
            startSlideshow()
        }
    }

    fun updateSelectedPerson(personId: String) {
        selectedPersonId = personId
        if (selectedImageType == ImageType.SPECIFIC_PERSON) {
            loadInitialAssets()
        }
    }
}

enum class ConnectionStatus {
    NOT_CONNECTED, CONNECTING, CONNECTED, FAILED
}